import React, { useEffect, useState } from "react";
import {
  LaptopOutlined,
  NotificationOutlined,
  UserOutlined,
  HomeOutlined,
  DatabaseOutlined,
  SmileOutlined,
  FunnelPlotOutlined,
  InboxOutlined,
  ApartmentOutlined,
  CloudDownloadOutlined,
  EnvironmentOutlined,
} from "@ant-design/icons";
import type { MenuProps } from "antd";
import {
  Breadcrumb,
  Layout,
  Menu,
  theme,
  Watermark,
  Modal,
  message,
} from "antd";

import LogoComponent from "@/components/Logo/index.tsx";

import { Outlet, useNavigate, useLocation } from "react-router-dom";

import routes from "@/router/index.tsx";

import styles from "./index.module.scss";
import { req } from "@/common/methods";
import pub from "@/units/pub";

const { Header, Content, Sider } = Layout;

let timerForGetState = undefined;

// const items2: MenuProps['items'] = [UserOutlined, LaptopOutlined, NotificationOutlined].map(
//   (icon, index) => {
//     const key = String(index + 1);

//     return {
//       key: `sub${key}`,
//       icon: React.createElement(icon),
//       label: `subnav ${key}`,

//       children: new Array(4).fill(null).map((_, j) => {
//         const subKey = index * 4 + j + 1;
//         return {
//           key: subKey,
//           label: `option${subKey}`,
//         };
//       }),
//     };
//   },
// );
const items2: MenuProps["items"] = [
  {
    key: "home",
    icon: <HomeOutlined />,
    label: "主页",
  },
  {
    key: "user",
    icon: <UserOutlined />,
    label: "用户中心",
    children: [
      {
        key: "user/change_password",
        label: "修改密码",
      },
      {
        key: "user/manage",
        label: "用户管理",
      },
    ],
  },
  {
    key: "category",
    icon: <FunnelPlotOutlined />,
    label: "分类管理",
  },
  {
    key: "lib",
    icon: <DatabaseOutlined />,
    label: "仓库管理",
    children: [
      {
        key: "lib/goods",
        label: "库存管理",
      },
      {
        key: "lib/in_storage",
        label: "入库单",
      },
      {
        key: "lib/in_storage/add",
        label: "新增入库单",
      },
      {
        key: "lib/out_storage",
        label: "出库单",
        // path:'goods/out'
      },
      {
        key: "lib/out_storage/add",
        label: "新增出库单",
      },
      {
        key: "lib/inventory",
        label: "盘点",
      },
      {
        key: "lib/history",
        label: "历史单据",
      },
      {
        key: "lib/accounts",
        label: "账表汇总",
      },
    ],
  },
  {
    key: "suppliers",
    icon: <InboxOutlined />,
    label: "供货商维护",
  },
  {
    key: "depart",
    icon: <ApartmentOutlined />,
    label: "部门维护",
  },
  {
    key: "export",
    icon: <CloudDownloadOutlined />,
    label: "数据导出",
  },
  {
    key: "about",
    icon: <SmileOutlined />,
    label: "关于",
  },
];

const App: React.FC = (props) => {
  const {
    token: { colorBgContainer },
  } = theme.useToken();
  const navigate = useNavigate();
  const location = useLocation();
  //console.log(location);
  const [menuSelectKeys, setMenuSelectKeys] = useState([]); //[1,2,3]
  const [breadItems, setBreadItems] = useState([]);
  useEffect(() => {
    //console.log('换');
    //更改菜单选项
    let targetMenuSelectKeys = [];
    items2.forEach((item3) => {
      if ("/management/" + item3.key === "" + location.pathname) {
        targetMenuSelectKeys.push(item3.key);
      }
      if (Array.isArray(item3.children)) {
        item3.children.forEach((item4) => {
          if ("/management/" + item4.key === "" + location.pathname) {
            targetMenuSelectKeys.push(item4.key);
          }
        });
      }
    });
    setMenuSelectKeys(targetMenuSelectKeys);
    //更新面包屑
    const { pathname } = location;
    const pathArr = pathname.split("/");
    //console.log(pathArr);
    const tarBreadItems = pathArr.map((item, index) => {
      let path = "";
      for (let i = 0; i <= index; i++) {
        //console.log(item,i)
        path = path + "/" + pathArr[i];
      }
      if (path.substring(0, 2) === "//") {
        path = path.substring(1);
      }
      //console.log('当前的path',path);
      return {
        href: "#" + path,
        title: (() => {
          let zTitle = "";
          routes.forEach((item1) => {
            //console.log(item1.path , path);
            if (item1.path === path) {
              //console.log(path,'')
              zTitle = item1.breadcrumbName || "未知页";
            }
            if (Array.isArray(item1.children)) {
              item1.children.forEach((item2) => {
                if (item1.path + "/" + item2.path === path) {
                  zTitle = item2.breadcrumbName || "未知页";
                }
              });
            }
          });
          if (!zTitle) {
            const items2Find = items2.find(
              (item4) => "/management/" + item4.key === path
            );
            if (items2Find) {
              zTitle = items2Find.label;
            } else {
              zTitle = "未知页面";
            }
          }
          return zTitle;
        })(),
      };
    });
    setBreadItems(tarBreadItems);
  }, [location.pathname]);
  //检测登录是否掉线的模块
  const getLoginState = () => {
    req("/api/get_login_state", {}, "post").then((data) => {
      if (!data.is_login) {
        Modal.confirm({
          title: "该页无法访问",
          content: <>您已掉线，请点击“确定”后重新登录使用</>,
          onOk() {
            navigate("/nologin");
            Modal.destroyAll();
          },
        });
      }
    });
  };
  useEffect(() => {
    clearInterval(timerForGetState);
    //getLoginState();
    timerForGetState = setInterval(() => {
      if (!document.querySelector("div#intervalgetstate")) {
        clearInterval(timerForGetState);
        return;
      }
      getLoginState();
    }, 10000);
  }, []);
  return (
    <>
      <Layout style={{ minHeight: "100vh" }}>
        <Header
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          <LogoComponent />
          <a
            href=""
            style={{ color: "lightgray" }}
            onClick={(e) => {
              e.preventDefault();
              Modal.confirm({
                title: "请确认",
                content: <>确定要退出登录吗？</>,
                onOk() {
                  req("/api/logout", {}, "post")
                    .then((data) => {
                      message.success("退出成功：" + data.result);
                      navigate("/nologin");
                    })
                    .catch((error) => {
                      Modal.error({
                        title: "错误",
                        content: <>该操作有可能导致退出失败,{"" + error}</>,
                      });
                    });
                },
              });
            }}
          >
            退出登录
          </a>
        </Header>
        <Layout>
          <Sider width={200} style={{ background: colorBgContainer }}>
            <Menu
              mode="inline"
              defaultSelectedKeys={["1"]}
              defaultOpenKeys={["user", "lib"]}
              style={{ height: "100%", borderRight: 0 }}
              items={items2}
              onClick={(e) => navigate(`/management/${e.key}`)}
              selectedKeys={menuSelectKeys}
            />
          </Sider>
          <Layout style={{ padding: "0 0px 0px" }}>
            <div className={styles["bread-package"]}>
              <EnvironmentOutlined />
              <Breadcrumb items={breadItems} style={{ margin: "16px 0" }} />
            </div>
            {/* <Breadcrumb style={{ margin: '16px 0' }}>
          </Breadcrumb> */}
            <Content
              style={{
                padding: 24,
                margin: 0,
                minHeight: 280,
                background: colorBgContainer,
              }}
            >
              <Watermark
                content="麟泽康养综合行政部"
                style={{ height: "100%" }}
              >
                <Outlet />
              </Watermark>
            </Content>
          </Layout>
        </Layout>
      </Layout>
      <div id="intervalgetstate" style={{ visibility: "hidden" }}></div>
    </>
  );
};

export default App;
